#include "mytcpserver.h"
#include "mytcpsocket.h"
#include <QThread>
MyTcpServer::MyTcpServer(QObject *parent) : QTcpServer(parent)
{

}

void MyTcpServer::socketDisconnectedSlot()
{
    QTcpSocket * socket = qobject_cast<QTcpSocket *>(sender());
   disconnect(socket,nullptr,nullptr,nullptr);
   disconnect(this,nullptr,socket,nullptr);
   QThread *th = socket->thread();
   socket->deleteLater();
   th->quit();

   connect(th,&QThread::finished,this,&MyTcpServer::threadFinishedSlot);

}

void MyTcpServer::threadFinishedSlot()
{
    QThread *th = qobject_cast<QThread *>(sender());
    disconnect(th,nullptr,nullptr,nullptr);
    th->deleteLater();
}

void MyTcpServer::incomingConnection(qintptr socketDescriptor)
{qDebug() << "jiangsheng";
   //创建socket
   MyTcpSocket *socket = new MyTcpSocket;
   if(socket == nullptr)
       return;
   socket->setSocketDescriptor(socketDescriptor);
   connect(socket, &MyTcpSocket::disconnected,this,&MyTcpServer::socketDisconnectedSlot);



   connect(socket,&MyTcpSocket::sendControlMessage,this,&MyTcpServer::sendControlMessage);
   connect(this,&MyTcpServer::sendControlMessage,socket,&MyTcpSocket::sendControlMessageSlot);
   connect(socket,&MyTcpSocket::deviceControlToOne,this,&MyTcpServer::deviceControlToOne);//绑定了socket的信号通过server转发给所有socket
   connect(this,&MyTcpServer::deviceControlToOne,socket,&MyTcpSocket::serverDeviceControlToOneSlot);

   //创建线程
   QThread *th = new QThread;
   if(th == nullptr)
   {
        socket->disconnectFromHost();
        socket->waitForDisconnected(500);
        socket->deleteLater();
        return;
   }
   th->start();
   socket->moveToThread(th);

}
















